//
//  CommonMethod.m
//  PensionTreasure
//
//  Created by Simon on 16/7/4.
//  Copyright © 2016年 柳宣泽. All rights reserved.
//

#import "CommonMethod.h"
#import "MBProgressHUD.h"

@implementation CommonMethod

+ (BOOL)isMobileNumer:(NSString *)mobileNum{
    if (mobileNum.length != 11){
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)){
        return YES;
    }else{
        return NO;
    }
}

+(BOOL)isHomeNumber:(NSString *)number{
    NSString *phoneRegex = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:number];
}

+ (BOOL)isEamilAvailable:(NSString *)emailAl{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:emailAl];
}

+ (BOOL)isHaveSpaceInstring:(NSString *)string{
    NSRange _range = [string rangeOfString:@" "];
    if (_range.location != NSNotFound) {
        return YES;
    }else {
        return NO;
    }
}

+ (BOOL)isHaveChineseInString:(NSString *)string{
    for(NSInteger i = 0; i < [string length]; i++){
        int a = [string characterAtIndex:i];
        if (a > 0x4e00 && a < 0x9fff) {
            return YES;
        }
    }
    return NO;
}

+ (BOOL)isPureInteger:(NSString *)string{
    NSScanner *scanner = [NSScanner scannerWithString:string];
    NSInteger val;
    return [scanner scanInteger:&val] && [scanner isAtEnd];
}

+ (NSString *)filterSpecialWithString:(NSString *)string{
    // 定义一个特殊字符的集合
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:
                           @"@／：；: ;（）?「」＂、[]{}#%-*+=_|~＜＞$?^?'@#$%^&*()_+'"];
    // 过滤字符串的特殊字符
    NSString *newString = [string stringByTrimmingCharactersInSet:set];
    return newString;
}

+(BOOL)CheckMoney:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField.text hasPrefix:@"."]) {
        textField.text = [NSString stringWithFormat:@"0%@",textField.text];
    }
    
    if ([textField.text hasPrefix:@"0"] &&
        textField.text.length == 1 &&
        [string isEqualToString:@"0"]) {
        return NO;
    }
    
    if ([textField.text hasPrefix:@"0"] &&
        textField.text.length == 1 &&
        ![string isEqualToString:@"0"] &&
        ![[textField.text stringByAppendingString:string] hasPrefix:@"0."]) {
        textField.text = [textField.text substringFromIndex:1];
    }
    
    int textNum = 10;
    NSRange textRange = [textField.text rangeOfString:@"."];
    if (textRange.location<=10) {
        textNum = 13;
    }else if(textField.text.length == 10 && [string isEqualToString:@"."])
    {
        return YES;
    }
    
    if (range.location >= textNum) {
        return NO;
    }else{
        BOOL isHasRadixPoint = YES;
        int RadixPointNum = 2;
        NSString *existText = textField.text;
        if ([existText rangeOfString:@"."].location == NSNotFound) {
            isHasRadixPoint = NO;
        }
        if (string.length > 0) {
            unichar newChar = [string characterAtIndex:0];
            if ((newChar >= '0' && newChar <= '9') || newChar == '.' ) {
                if (newChar == '.') {
                    if (isHasRadixPoint)
                        return NO;
                    else
                        return YES;
                }else {
                    if (isHasRadixPoint) {
                        NSRange ran = [existText rangeOfString:@"."];
                        unsigned long radixPointCount = range.location - ran.location;
                        if (radixPointCount <= RadixPointNum) return YES;
                        else return NO;
                    } else
                        return YES;
                }
            }else {
                return NO;
            }
        }else {
            return YES;
        }
    }
}

+ (void)showToast:(NSError *)error{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = [CommonMethod showErrorMessage:error];
    hud.alpha = 0.6;
    hud.margin = 10.f;
    hud.yOffset = 0.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:3];
}

+(void)showToast1:(NSString *)msg{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].delegate.window animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.labelText = msg;
    hud.alpha = 0.6;
    hud.margin = 10.f;
    hud.yOffset = 0.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:3];
}

+ (NSString *)showErrorMessage:(NSError *)error{
    NSString *errorName =[[error userInfo] objectForKey:@"error_description"];
    NSString *errorCode = [[error userInfo] objectForKey:@"error_code"];
    NSString *errorName_Code = [NSString stringWithFormat:@"%@ [ %@ ]",errorName,errorCode];
    NSString *errorLeaveName_Code = [NSString stringWithFormat:@"登录失效，请重新登录！［%@］",errorCode];
    
    if ([[[error userInfo] objectForKey:@"error_description"] length]==0 && [[[error userInfo] objectForKey:@"error_code"] length]==0){
        NSString *message = [error localizedDescription];
        if ([message isEqualToString:@"Could not connect to the server."]) {
            message = @"无法连接服务器!";
        }else if([message isEqualToString:@"The request timed out."])
        {
            message = @"连接服务器超时!";
        }else if([message isEqualToString:@"The operation couldn’t be completed."])
        {
            message = errorName;
        }else if ([message isEqualToString:@"The Internet connection appears to be offline."])
        {
            message = @"网络链接失败，请检查网络";
        }else if ([message isEqualToString:@"The network connection was lost."])
        {
            message = @"网络链接失败，请检查网络";
        }
        return message;
    }else{
        if ([errorName containsString:@"验证码错误.动态验证码错误"])  {
            return [errorName stringByReplacingOccurrencesOfString:@".动态验证码错误" withString:@""];
        }
        if ([errorName isEqualToString:@"您的账号已在别处登录，请注意账号安全！"] || [errorName isEqualToString:@"登录失效，请重新登录！"] || [errorCode isEqualToString:@"ASR-000003"] || [errorCode isEqualToString:@"ERH-000003"] || [errorCode isEqualToString:@"ASR-000004"] || [errorCode isEqualToString:@"ERH-000004"] || [errorCode isEqualToString:@"ASR-000005"] || [errorCode isEqualToString:@"ERH-000005"] || [errorCode isEqualToString:@"ASR-000006"] || [errorCode isEqualToString:@"ERH-000006"] || [errorCode isEqualToString:@"invalid_token"]|| [errorCode isEqualToString:@"invalid_grant"]) {
            
            NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
            NSArray *_tmpArray = [NSArray arrayWithArray:[cookieJar cookies]];
            for (id obj in _tmpArray) {
                [cookieJar deleteCookie:obj];
            }
            return errorLeaveName_Code;
        }else{
            return errorName_Code;
        }
    }
}

/*
+(BOOL)userNameIsRightInputWithString:(NSString*)string{
    if(string.length <=1 && (string.length >=100 && ![string isEqualToString:@""])){
        return NO;
    }
    NSCharacterSet *cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:MAYUSERDCHARACTER] invertedSet];
    //invertedSet 方法是去反字符,把所有的除了数字的字符都找出来
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    //componentsSeparatedByCharactersInSet 方法是把输入框输入的字符string 根据cs中字符一个一个去除cs字符并分割成单字符并转化为 NSArray, 然后componentsJoinedByString 是把NSArray 的字符通过 ""无间隔连接成一个NSString字符 赋给filtered.就是只剩数字了.
    BOOL basicTest = [string isEqualToString:filtered];
    if(!basicTest){
        [self showToast1:@"请输入数字字母或者下划线"];
        return NO;
    }
    return basicTest;
}
*/

+(NSString*)createUUID {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

//不同基金公司的数据颜色是不一样的
/*
 +(UIColor *)getTheColor{
 if ([FUNDMANAGER.centerFundInfo.corpCode isEqualToString:@"01"]) {
 return [UIColor colorWithHexString:FUNDA_COLOR];
 }
 if ([FUNDMANAGER.centerFundInfo.corpCode isEqualToString:@"02"]) {
 return [UIColor colorWithHexString:FUNDB_COLOR];
 }
 
 return [UIColor colorWithHexString:@"c43019"];
 }
 */

+ (NSString*)getDateStringFromTimeInterval:(NSString*)timeIntervalString {
    NSString *result = nil;
    if (timeIntervalString) {
        NSString *str =  [timeIntervalString stringByReplacingOccurrencesOfString:@"," withString:@""];
        double time = [str doubleValue]/1000;
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *format= [[NSDateFormatter alloc] init];
        format.dateFormat = @"yyyy-MM-dd";
        result = [format stringFromDate:date];
    }
    return result;
}


+ (NSString *)formattedDigitalComputingAlgorithm:(NSString *)algorithmMode firstNumber:(NSString *)firstNum secondNumber:(NSString *)secondNum andScale:(int)scale{
    /*
     1.RoundingMode:
     NSRoundPlain：四舍五入
     NSRoundDown：超过的位数都舍弃
     NSRoundUp：超过的位数向前进1
     NSRoundBankers：
     2.scale：就是保留几位小数
     3.raiseOnExactness：如果设置为YES，当精确度发生错误的时候会抛出异常，否则就直接返回NAN
     4.raiseOnOverflow：如果设置为YES，当发生溢出时会抛出异常，否则就直接返回NAN
     5.raiseOnUnderflow：如果设置为YES，当发生下溢时会抛出异常，否则就直接返回NAN
     6.raiseOnDivideByZero：如果设置为YES，当除以0时会抛出异常，否则就直接返回NAN
     */
    
    firstNum = [firstNum stringByReplacingOccurrencesOfString:@"," withString:@""];
    
    NSDecimalNumberHandler*roundMode = [NSDecimalNumberHandler
                                        
                                        decimalNumberHandlerWithRoundingMode:NSRoundDown
                                        
                                        scale:scale
                                        
                                        raiseOnExactness:NO
                                        
                                        raiseOnOverflow:NO
                                        
                                        raiseOnUnderflow:NO
                                        
                                        raiseOnDivideByZero:YES];
    
    NSDecimalNumber *firstDecimalNum = [NSDecimalNumber decimalNumberWithString:firstNum];
    NSDecimalNumber *secondDecimalNum = [NSDecimalNumber decimalNumberWithString:secondNum];
    NSDecimalNumber *operationResult = nil;
    if ([algorithmMode isEqualToString:@"Add"] || [algorithmMode isEqualToString:@"+"]) {
        operationResult = [firstDecimalNum decimalNumberByAdding:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Subtract"]  || [algorithmMode isEqualToString:@"-"]){
        operationResult = [firstDecimalNum decimalNumberBySubtracting:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Multiply"]  || [algorithmMode isEqualToString:@"*"]){
        operationResult = [firstDecimalNum decimalNumberByMultiplyingBy:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Divide"]  || [algorithmMode isEqualToString:@"/"]){
        operationResult = [firstDecimalNum decimalNumberByDividingBy:secondDecimalNum withBehavior:roundMode];
    }
    
    NSString* string = [NSString stringWithFormat:@"%@",operationResult];
    
//    if ([string rangeOfString:@"."].length==0) {
//        
//        string=  [string stringByAppendingString:@".0000"];
//    }else{
//        NSRange range = [string rangeOfString:@"."];
//        
//        if (string.length-range.location-1==2) {
//            
//        }else{
//            string=   [string stringByAppendingString:@"0"];
//        }
//    }
    return string;
}



+ (NSString *)formattedDigitalComputingAlgorithm:(NSString *)algorithmMode firstNumber:(NSString *)firstNum secondNumber:(NSString *)secondNum{
    /*
     1.RoundingMode:
     NSRoundPlain：四舍五入
     NSRoundDown：超过的位数都舍弃
     NSRoundUp：超过的位数向前进1
     NSRoundBankers：
     2.scale：就是保留几位小数
     3.raiseOnExactness：如果设置为YES，当精确度发生错误的时候会抛出异常，否则就直接返回NAN
     4.raiseOnOverflow：如果设置为YES，当发生溢出时会抛出异常，否则就直接返回NAN
     5.raiseOnUnderflow：如果设置为YES，当发生下溢时会抛出异常，否则就直接返回NAN
     6.raiseOnDivideByZero：如果设置为YES，当除以0时会抛出异常，否则就直接返回NAN
     */
    
    firstNum = [firstNum stringByReplacingOccurrencesOfString:@"," withString:@""];

    NSDecimalNumberHandler*roundMode = [NSDecimalNumberHandler
                                      
                                      decimalNumberHandlerWithRoundingMode:NSRoundDown
                                      
                                      scale:2
                                      
                                      raiseOnExactness:NO
                                      
                                      raiseOnOverflow:NO
                                      
                                      raiseOnUnderflow:NO
                                      
                                      raiseOnDivideByZero:YES];
    
    NSDecimalNumber *firstDecimalNum = [NSDecimalNumber decimalNumberWithString:firstNum];
    NSDecimalNumber *secondDecimalNum = [NSDecimalNumber decimalNumberWithString:secondNum];
    NSDecimalNumber *operationResult = nil;
    if ([algorithmMode isEqualToString:@"Add"] || [algorithmMode isEqualToString:@"+"]) {
        operationResult = [firstDecimalNum decimalNumberByAdding:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Subtract"]  || [algorithmMode isEqualToString:@"-"]){
        operationResult = [firstDecimalNum decimalNumberBySubtracting:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Multiply"]  || [algorithmMode isEqualToString:@"*"]){
        operationResult = [firstDecimalNum decimalNumberByMultiplyingBy:secondDecimalNum withBehavior:roundMode];
    }else if ([algorithmMode isEqualToString:@"Divide"]  || [algorithmMode isEqualToString:@"/"]){
        operationResult = [firstDecimalNum decimalNumberByDividingBy:secondDecimalNum withBehavior:roundMode];
    }
    
    NSString* string = [NSString stringWithFormat:@"%@",operationResult];
    
    if ([string rangeOfString:@"."].length==0) {
        
        string=  [string stringByAppendingString:@".00"];
    }else{
        NSRange range = [string rangeOfString:@"."];
        
        if (string.length-range.location-1==2) {
        
        }else{
            string=   [string stringByAppendingString:@"0"];
        }
    }
    return string;
}

+(NSString *)queryValueFromUserDefaultWithKey:(NSString *)key{
    if (key) {
        return [[NSUserDefaults standardUserDefaults] objectForKey:key];
    }else
        return nil;
}


+(void)setValueToUserDefaultObject:(NSString *)value WithKey:(NSString *)key{
    if (value&&key) {
        [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }else{
        return;
    }
}

+(NSString * )getNowTimeStringWithFormat:(NSString*)format{
    NSDateFormatter *formatDay = [[NSDateFormatter alloc] init];
    formatDay.dateFormat = format;
    NSString * rule = [formatDay stringFromDate:[NSDate date]];
    return rule;
}


+(NSString * )pointTwoFloatString :(NSString *)pointString
{
   
    NSString *string = [NSString stringWithFormat:@"%.2lf",[pointString doubleValue]];
    return string;
}
@end
